using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.VisualStudio.DebuggerVisualizers;
using Microsoft.SharePoint;
using System.Data;

namespace SPDV
{
    public class SPListObjectProvider : VisualizerObjectSource
    {
        public override void GetData(object target, System.IO.Stream outgoingData)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(outgoingData, GetSerializableObject((SPList) target));
        }
        private SPListData GetSerializableObject(SPList list)
        {
            if (null == list) return null;
            SPListData spld = new SPListData();
            spld.Title = list.Title;
            spld.ID = list.ID;
            spld.Description = list.Description;
            foreach (SPField f in list.Fields)
            {
                //Whatch out when using SPField.Title, duplicates might appear
                spld.folders.Columns.Add(f.InternalName);
                spld.items.Columns.Add(f.InternalName);
            }
            foreach (SPListItem i in list.Folders)
            {
                DataRow dr = spld.folders.NewRow();
                foreach (DataColumn dc in spld.folders.Columns)
                    dr[dc.ColumnName] = i[dc.ColumnName];
                spld.folders.Rows.Add(dr);
            }
            foreach (SPListItem i in list.Items)
            {
                DataRow dr = spld.items.NewRow();
                foreach (DataColumn dc in spld.items.Columns)
                    dr[dc.ColumnName] = i[dc.ColumnName];
                spld.items.Rows.Add(dr);
            }
            //add the folder-items relation
            if ((null != spld.folders.Columns["ID"]) && (null != spld.items.Columns["ParentFolderId"]))
                spld.ds.Relations.Add("folder2item", spld.folders.Columns["ID"], spld.items.Columns["ParentFolderId"]);
            return spld;
        }
    }
}